package scale.sim;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

import scale.data.Scale;

public class ScaleServer  implements Runnable{

	private static final int defaultPort = 8000;
	private ServerSocket socket;
	private int port;
	private ArrayList<RemoteSession> clients = new ArrayList<RemoteSession>();

	public Scale scale;
	
	/**
	 * Starts the Scale Server on port 8000
	 */
	public ScaleServer() {
		this(defaultPort);
	}

	/**
	 * Starts the Scale Server on a given port
	 * @param port
	 */
	public ScaleServer(int port) {
		scale = new Scale();
		this.port = port;
	}
	
	@Override
	public void run() {
		try {
			// Print welcome text
			System.out.println("Waiting on port " + port);

			// Start listener for socket connections
			socket = new ServerSocket(port);

			while (true) {
				System.out.println("Waiting for new connections...");
				Socket s = socket.accept(); // Waiting for new connection
				System.out.print("New connection!... ");
				RemoteSession rs = new RemoteSession(s, scale);

				clients.add(rs); // Adds the new RemoteSession to the list
									// clients

				Thread t = new Thread(rs);
				t.start(); // Start the new Thread

				System.out.println(rs.getSocket().getRemoteSocketAddress()
						+ " connected!");
			}

		} catch (Exception e) {
			for (RemoteSession rcs : clients) { // Loops clients connected
				if (rcs.getSocket().isClosed()) {
					System.out.println(rcs.getSocket().getRemoteSocketAddress()
							+ " connection lost!");
					clients.remove(rcs);
				}
			}
		}
	
	}
}
